package com.yxhl.zoume.core.tripsmgmt.ui.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.yxhl.zoume.R;
import com.yxhl.zoume.utils.CollectionUtils;
import com.yxhl.zoume.utils.EncodeHelper;
import com.yxhl.zoume.utils.LOG;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by vhawk on 16/5/24.
 */
public class TicketQRAdapter extends PagerAdapter {

    private static final String TAG = "TicketQRAdapter";
    private List<String> ticketCodeList;
    private Context context;
    private List<View> viewList = new ArrayList<>();

    public TicketQRAdapter(Context context, List<String> ticketCodeList) {
        this.context = context;
        this.ticketCodeList = ticketCodeList;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);
        container.removeView(viewList.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View view = View.inflate(context, R.layout.item_trip_mgmt_ticket, null);
        initTicketCodeIv(position, view);
        initTicketCodeTv(position, view);
        container.addView(view);
        viewList.add(position, view);
        LOG.v(TAG, "count = " + container.getChildCount());
        LOG.v(TAG, "position = " + position);
//        return ticketCodeList.get(position);
        return view;
    }

    private void initTicketCodeTv(int position, View view) {
        TextView ticketCodeTv = (TextView) view.findViewById(R.id.tv_generate_ticket);
        ticketCodeTv.setText("乘车码: " + ticketCodeList.get(position));
    }

    private void initTicketCodeIv(int position, View view) {
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_picture);
        Bitmap qrCodeBitmap = null;
        try {
            //noinspection AccessStaticViaInstance
            qrCodeBitmap = EncodeHelper.createQRCode(ticketCodeList.get(position), 350);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        imageView.setImageBitmap(qrCodeBitmap);
    }

    @Override
    public int getCount() {
        if (CollectionUtils.isEmpty(ticketCodeList)) {
            return 0;
        }
        return ticketCodeList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
